use serde::de::{MapAccess, Visitor};
use serde::Deserialize;
use serde::Deserializer;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs;

#[derive(Debug, Deserialize)]
struct Provice {
    #[serde(rename(deserialize = "name"))]
    name: String,
    #[serde(rename(deserialize = "type"))]
    entry_type: String,
    #[serde(rename(deserialize = "cities"), default)]
    cities: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct Data {
    #[serde(rename(deserialize = "provices"))]
    entries: Vec<Provice>,
}

#[derive(Debug, Deserialize)]
struct InputData(HashMap<usize, Entity>);

#[derive(Debug)]
struct Entity {
    entry: HashMap<String, Vec<String>>,
}

impl<'de> Deserialize<'de> for Entity {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EntityVisitor;

        impl<'de> Visitor<'de> for EntityVisitor {
            type Value = Entity;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a map of Entity")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut entry = HashMap::new();

                while let Some((key, values)) = map.next_entry::<String, Vec<String>>()? {
                    entry.entry(key).or_insert_with(Vec::new).extend(values);
                }

                Ok(Entity { entry })
            }
        }

        deserializer.deserialize_map(EntityVisitor)
    }
}

pub fn count_provinces() -> String {
    let special = vec!["北京", "上海", "天津", "重庆", "香港", "澳门"];
    let data = parse_data();
    let input = parse_input();
    let mut ans = vec![0; input.0.len()];

    for (number, entity) in input.0.iter() {
        let mut set = HashSet::new();
        // println!("province_key: {}", number);

        for city_key in entity.entry.keys() {
            // println!("city_key: {}", city_key);

            for province in data.entries.iter() {
                // // 直辖市或者特别行政区
                if special.contains(&city_key.as_str()) {
                    // println!("直辖市或者特别行政区: {}", city_key);
                    set.insert(city_key);
                }
                // 直辖市的区或者特别行政区的区
                else if province.cities.contains(&city_key) {
                    // println!("直辖市的区或者特别行政区的区: {}", province.name);
                    set.insert(&province.name);
                } else {
                    for city in province.cities.iter() {
                        if city == city_key {
                            // println!("省份城市: {}", province.name);
                            set.insert(&province.name);
                        }
                    }
                }
            }
        }
        // println!("set: {:?}", set);
        ans[*number - 1] = set.len();
    }
    ans.iter()
        .map(|x| x.to_string())
        .collect::<Vec<String>>()
        .join(",")
}
fn parse_input() -> InputData {
    let input = fs::read_to_string("district.json").expect("file not found");
    let data: InputData = serde_json::from_str(&input).unwrap();
    // println!("{:?}", data);
    data
}
//topic1/solutiont2/src/
fn parse_data() -> Data {
    let data = std::fs::read_to_string("data.json").expect("file not found");
    let entity: Data = serde_json::from_str(&data).expect("parse error");
    // println!("{:?}", entity);
    entity
}
